package com.yc.springcloud.controller;

import com.yc.springcloud.entity.Member;
import com.yc.springcloud.service.MemberOpenFeignService;
import com.yc.springcloud.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

/**
 * @Author DELL
 * @Date 2024/10/4 16:30
 * @Version 1.0
 */
@Slf4j
@Controller
public class MemberConsumerController {

	//指向member_service_provider、
	public static final String MEMBER_SERVICE_PROVIDER =
			"http://MEMBER-SERVICE-PROVIDER";  //提供服务的注册别名

	@Resource
	private RestTemplate restTemplate;

	//DiscoveryClient 接口
	@Resource
	private DiscoveryClient discoveryClient;


	//OpenFeign接口
	@Resource
	private MemberOpenFeignService memberOpenFeignService;

	@ResponseBody
	@GetMapping(value = "/member/openfeign/consumer/get/{id}")
	public Result<Member> getMemberOpenfeignById(@PathVariable("id") Long id){

		System.out.println("通过 openfeignd+负载均衡 调用服务");
		//获得openFeign
		Result<Member> memberOpenfeignById = memberOpenFeignService.getMemberById(id);
		return memberOpenfeignById;
	}

	@ResponseBody
	@GetMapping(value = "/member/consumer/get/{id}")
	public Result<Member> queryMemberById(@PathVariable("id") Long id){

		log.info("id=",id);
		//访问member_service_provider-001 的queryMemberById接口n
		String MEMBER_SERVICE_PROVIDER_URL =
				MEMBER_SERVICE_PROVIDER + "/member/get/" + id;

		log.info(MEMBER_SERVICE_PROVIDER_URL);
		return restTemplate.getForObject(MEMBER_SERVICE_PROVIDER_URL,Result.class);

	}

	@ResponseBody
	@GetMapping(value = "/member/consumer/discovery")
	public Object getDiscovery(){

		List<String> services = discoveryClient.getServices();
		for (String service : services) {
			List<ServiceInstance> serviceInstance = discoveryClient.getInstances(service);
			for (ServiceInstance instance : serviceInstance) {
				log.info("instance = ",instance);
				String host = instance.getHost();
				String instanceId = instance.getInstanceId();
				int port = instance.getPort();
				URI uri = instance.getUri();
				System.out.println("host:"+ host + "--instanceId:" + instanceId + "--port:" + port + "--uri:" + uri);

			}
		}
		return this.discoveryClient;
	}





}
